package cn.cxyxj.code_resource_prod.code_resource.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * @author cxyxj
 */
@Component
public class SpringUtil implements ApplicationContextAware {

   private static final Logger logger = LoggerFactory.getLogger(SpringUtil.class);

   private static ApplicationContext applicationContext;

   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      SpringUtil.applicationContext = applicationContext;
   }

   public static  <T> T getBean(String name, Class<T> requiredType) throws BeansException {
      return applicationContext.getBean(name, requiredType);
   }

   public static <T> T getBean(String name) throws BeansException {
      return (T) applicationContext.getBean(name);
   }

   public static <T> T getBean(Class<T> clz) throws BeansException {
      return applicationContext.getBean(clz);
   }

   public static void publishEvent(ApplicationEvent event) {
      if (applicationContext != null) {
         try {
            applicationContext.publishEvent(event);
         } catch (Exception ex) {
            logger.error("[publishEvent]，spring事件发布异常,event={}", JSON.toJSONString(event),ex);
         }
      }
   }

}
